package lockDemo;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Ajie
 * @date 8/12/21
 * @function
 * Condition VS wait/notify
 * Condition 就可以明确的指定唤醒读线程。
 */
public class ConditionDemo {
    public static void main(String[] args) throws InterruptedException {
        final OfficeWork work = new OfficeWork();
        new Thread() {
            public void run() {
                work.coderCmd();
            }
        }.start();

        new Thread() {
            public void run() {
                work.teamLeaderCmd();
            }
        }.start();

        new Thread() {
            public void run() {
                work.managerCmd();
            }
        }.start();

        Thread.sleep(2000);
        work.bossCmd();
    }

    static class OfficeWork {
        private Lock lock = new ReentrantLock();
        private Condition cond1 = lock.newCondition();
        private Condition cond2 = lock.newCondition();
        private Condition cond3 = lock.newCondition();

        public void bossCmd() {
            try {
                lock.lock();
                System.out.println("Boss have a plain!");
                cond1.signal();
            } finally {
                lock.unlock();
            }
        }

        public void managerCmd() {
            try {
                lock.lock();
                cond1.await();
                Thread.sleep(500);
                System.out.println("Manager received Cmd!");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                cond3.signal();
                lock.unlock();
            }
        }

        public void coderCmd() {
            try {
                lock.lock();
                cond2.await();
                Thread.sleep(500);
                System.out.println("Coder received Cmd!");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                cond1.signal();
                lock.unlock();
            }
        }

        public void teamLeaderCmd() {
            try {
                lock.lock();
                cond3.await();
                Thread.sleep(500);
                System.out.println("TeamLeader received Cmd!");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                cond2.signal();
                lock.unlock();
            }
        }
    }

}
